import { isArray, isNullOrEmpty, isObject, isSetObject } from './index'
import { tabPageList } from '../config'
import navigationConfig from '@/components/al-navigation/config'
import { apiHost } from '@/config';
import { useUserStoreWithOut } from '@/store/modules/user';

// 获取应用ID
export function $getPublishedApplicationId(): number {
    try {
        const { pathname } = window.location
        const applicationID = pathname.split('/')[1].replace('app_', '')
        return Number(applicationID)
    } catch (e) {
        return 0
    }
}

/**
 * 数组/对象遍历
 * @param object 要遍历的对象
 * @param formatCallback 要执行的方法
 */
export function $each<T = any>(
    object: Array<T> | Record<string, T> | Set<T>,
    formatCallback: (item: T, index?: number | string) => void
) {
    let index: number | string | T = 0
    if (isArray<T>(object)) {
        // Object 没有length, 只有 Array 有
        const { length } = object
        for (; index < length; index++) {
            formatCallback(object[index], index)
        }
    } else if (isSetObject<T>(object)) {
        for (index of object) {
            formatCallback(index)
        }
    } else if (isObject<T>(object)) {
        for (index in object) {
            formatCallback(object[index], index)
        }
    }
}

/**
 * 持久化信息
 * @param key 存储的key
 * @param content 存储的内容
 */
export function localSave(key: string, content: any) {
    uni.setStorageSync(
        key,
        JSON.stringify({
            expire: Date.now() + 1000 * 60 * 60 * 8,
            value: content
        })
    )
}

/**
 * 获取持久化信息
 * @param key 存储的key
 */
export function localGet(key: string) {
    try {
        const result = JSON.parse(uni.getStorageSync(key) || '{}')
        if (result.hasOwnProperty('value')) {
            return result.value
        } else {
            return result
        }
    } catch (error) {
        return
    }
}

/**
 * 通用 Storage 存储
 * @param dataKey 存储的key
 * @param value 存储的内容，标准JSON对象
 * @returns {boolean} 存储是否成功
 */
export function setStorage(dataKey: string, value: any) {
    try {
        return uni.setStorageSync(dataKey, JSON.stringify(value))
    } catch (error) {
        return false
    }
}
/*
 * 获取存储内容
 * @param dataKey 存储的key
 * @returns {any} 存储的对象
 */
export function getStorageByKey(dataKey: string) {
    try {
        const data = uni.getStorageSync(dataKey)
        if (!isNullOrEmpty(data)) {
            return JSON.parse(data as string)
        }
        return null
    } catch (error) {
        return null
    }
}
/**
 * 处理页面跳转
 * @param {String} href 目标URL
 */
export function handleRedirect(href: string) {
    // 提取URL部分
    const pureURL = href.split('?')[0]
    const isLeftNavigation = navigationConfig && navigationConfig.position && navigationConfig.position === 'left'
    if (tabPageList.includes(pureURL) && !isLeftNavigation) {
        uni.switchTab({
            url: pureURL
        })
    } else {
        uni.navigateTo({
            url: href,
            fail: function (res) {
                uni.navigateTo({ url: '/pages/NoPage/NoPage' });
                console.warn(res);
            }
        });
    }
}

/**
 * 处理页面跳转
 * @param {String} href 目标URL
 */
export function handleRedirectForNav(settingId: String, customUrl: String) {
    const url = customUrl ? customUrl : `/pages/Page${settingId}/Page${settingId}`;
    uni.redirectTo({
        url: url
    })
}

/**
 * 获取PC与移动端产品ID映射map
 * 暂时简单使用uni.request，后续boss映射开发后可去掉(小程序不可使用fetch调用)
 */
export async function getProductIdMap() {
    return new Promise((resolve, reject) => {
        uni.request({
            url: `${apiHost}/productIdMap.json`,
            method: 'GET',
            success: res => {
                resolve(res.data)
            },
            fail: err => {
                reject(err)
            }
        })
    })
}

/**
 * 判断是否有权限
 */
export function permission(permissionVal: string | number) {
    const userStore = useUserStoreWithOut();
    const permissionCodeMap: string[] = userStore.getPermissionCodeMap || [];
    if (permissionCodeMap.includes(String(permissionVal))) {
        return true;
    }
    return false;
}
